package com.sxdz.pay.service

import com.sxdz.constant.GlobalConstant
import com.sxdz.pay.util.SignUtils
import com.google.gson.Gson
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.CloseableHttpClient
import com.sxdz.pay.util.XmlUtils
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils

import javax.servlet.ServletException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * Created by lijm on 2015/6/23.
 */
class GateWayService {

    private final static String version = "1.0";
    private final static String charset = "UTF-8";
    private final static String sign_type = "MD5";

    public void pay(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("===============支付请求...==========================");
        SortedMap<String, String> map = XmlUtils.getParameterMap(req);

        map.put("service", "pay.weixin.jspay");
        map.put("version", version);
        map.put("charset", charset);
        map.put("sign_type", sign_type);

        map.put("mch_id", GlobalConstant.getString("mch_id"));
        map.put("notify_url", GlobalConstant.getString("notify_url"));
        System.out.println("==============url:================="+GlobalConstant.getString("notify_url"));
        map.put("callback_url", GlobalConstant.getString("callback_url"));
        map.put("nonce_str", String.valueOf(new Date().getTime()));

        Map<String, String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        String sign = MD5.sign(preStr, "&key=" + GlobalConstant.getString("key"), "utf-8");
        map.put("sign", sign);

        String reqUrl = GlobalConstant.getString("req_url");
        log.info("reqUrl：" + reqUrl);

        log.info("reqParams:" + XmlUtils.parseXML(map));
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        String res = null;
        Map<String, String> resultMap = null;
        try {
            HttpPost httpPost = new HttpPost(reqUrl);
            StringEntity entityParams = new StringEntity(XmlUtils.parseXML(map), "utf-8");
            httpPost.setEntity(entityParams);
            httpPost.setHeader("Content-Type", "text/xml;charset=ISO-8859-1");
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            if (response != null && response.getEntity() != null) {
                resultMap = XmlUtils.toMap(EntityUtils.toByteArray(response.getEntity()), "utf-8");
                res = XmlUtils.toXml(resultMap);
                log.info("请求结果：" + res);
                if (!SignUtils.checkParam(resultMap, GlobalConstant.getString("key"))) {
                    res = "验证签名不通过";
                } else {
                    if ("0".equals(resultMap.get("status")) && "0".equals(resultMap.get("result_code"))) {
                        String code_img_url = resultMap.get("code_img_url");
                        log.debug("code_img_url : " + code_img_url);
                        res = "ok";
                    }
                }
            } else {
                res = "操作失败";
            }
        } catch (Exception e) {
            log.info("操作失败，原因：",e);
            res = "系统异常";
        } finally {
            if (response != null) {
                response.close();
            }
            if (client != null) {
                client.close();
            }
        }
        Map<String,String> result = new HashMap<String,String>();
        if("ok".equals(res)){
            result = resultMap;
        }else{
            result.put("status", "500");
            result.put("msg", res);
        }
        resp.getWriter().write(new Gson().toJson(resultMap));
    }

}
